<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="primary" size="mini" @click="navigateTo('./add')">新增</button>
				<button class="uni-button" type="warn" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button>
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">导出 Excel</button>
				</download-excel>
				<button class="uni-button" type="primary" size="mini">从Excel导入</button>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList"
				field="storage_id{_id,storageName,area},totalClassify_id{_id,totalKeyName,totalKeyValue},classify_id{_id,classifyName,classifyNickName,directoryCategories,directoryIndex},firm_id{_id,firmName},equipmentName,imgFile,storageState,equipmentStateInfo,purchaseTime,overInsuranceTime"
				:where="where" page-data="replace" :orderby="orderby" :getcount="true" :page-size="options.pageSize"
				:page-current="options.pageCurrent" v-slot:default="{data,pagination,loading,error,options}"
				:options="options" loadtime="manual" @load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center">资产编码</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'storage_id')">所属仓库</uni-th>
						<uni-th align="center" sortable
							@sort-change="sortChange($event, 'totalClassify_id')">总类</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'classify_id')">装备类型</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'firm_id')">厂商</uni-th>
						<uni-th align="center">目录类别</uni-th>
						<uni-th align="center" filter-type="search"
							@filter-change="filterChange($event, 'equipmentName')" sortable
							@sort-change="sortChange($event, 'equipmentName')">装备名称</uni-th>
						<uni-th align="center">装备图片</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'storageState')">在库状态</uni-th>
						<uni-th align="center" filter-type="select"
							:filter-data="options.filterData.equipmentStateInfo_localdata"
							@filter-change="filterChange($event, 'equipmentStateInfo')">装备状态信息</uni-th>
						<uni-th align="center">资产编号</uni-th>
						<uni-th align="center" filter-type="timestamp"
							@filter-change="filterChange($event, 'purchaseTime')" sortable
							@sort-change="sortChange($event, 'purchaseTime')">装备购入时间</uni-th>
						<uni-th align="center" filter-type="timestamp"
							@filter-change="filterChange($event, 'overInsuranceTime')" sortable
							@sort-change="sortChange($event, 'overInsuranceTime')">装备过保时间</uni-th>
						<uni-th align="center" width="150px">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">
							{{"GZ·"+item.classify_id[0].classifyNickName+'/'+item.totalClassify_id[0].totalKeyName+item.classify_id[0].directoryIndex+'-'+getIdLastThree(item._id)+'·'+item.storage_id[0].area}}
						</uni-td>
						<uni-td align="center">{{item.storage_id[0].storageName}}</uni-td>
						<uni-td align="center">
							<el-tag :type="tagTotalClassifyContent(item.totalClassify_id[0].totalKeyName)">
								{{item.totalClassify_id[0].totalKeyValue + "_" + item.totalClassify_id[0].totalKeyName}}
							</el-tag>
						</uni-td>
						<uni-td align="center">{{item.classify_id[0].classifyName}}</uni-td>
						<uni-td align="center">{{item.firm_id[0].firmName}}</uni-td>
						<uni-td align="center">
							<el-tag
								:type="tagCategoryContent(item.classify_id[0].directoryCategories)">{{item.classify_id[0].directoryCategories}}</el-tag>
						</uni-td>
						<uni-td align="center">{{item.equipmentName}}</uni-td>
						<uni-td align="center">
							<el-image style="width: 50px; height: 50px;" :src="item.imgFile.url"
								:preview-src-list="[item.imgFile.url]" :hide-on-click-modal="true"
								fit="fill"></el-image>
						</uni-td>
						<uni-td align="center">
							<el-tag :type="tagStorageContent(item.storageState)" effect="dark">
								{{item.storageState == true ? "在库" : "出库"}}
							</el-tag>
						</uni-td>
						<uni-td align="center">
							<view class="equipmentStateInfo">
								<uni-icons type="smallcircle-filled" size="16"></uni-icons>
								<text>{{options.equipmentStateInfo_valuetotext[item.equipmentStateInfo]}}</text>
							</view>
						</uni-td>
						<uni-td align="center">{{item._id}}</uni-td>
						<uni-td align="center">
							<uni-dateformat :threshold="[0, 0]" :date="item.purchaseTime"></uni-dateformat>
						</uni-td>
						<uni-td align="center">
							<uni-dateformat :threshold="[0, 0]" :date="item.overInsuranceTime"></uni-dateformat>
						</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<el-button type="success" icon="FullScreen" circle
									@click="createQRCode(item._id)"></el-button>
								<el-button type="primary" icon="Edit" @click="navigateTo('./edit?id='+item._id, false)"
									circle />
								<el-button type="danger" icon="Delete" @click="confirmDelete(item._id)" circle />
								<!-- <button @click="" class="uni-button" size="mini"
									type="primary">修改</button>
								<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
									type="warn">删除</button> -->
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
		<uni-popup ref="qrcodePopup" background-color="#fff">
			<view class="qrcodeContainer">
				<!-- <canvas id="qrcode" canvas-id="qrcode" style="width: 200px;height: 200px;"></canvas> -->
				<uqrcode ref="uqrcode" canvas-id="qrcode" :value="qrcodeID" :auto="true"></uqrcode>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '@/js_sdk/validator/tab_EquipmentInfo.js';
	// import UQRCode from '@/uni_modules/Sansnn-uQRCode/js_sdk/uqrcode/uqrcode.js';
	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = '' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				collectionList: [
					db.collection('tab_EquipmentInfo').field(
						'storage_id,totalClassify_id,classify_id,firm_id,equipmentName,imgFile,storageState,equipmentStateInfo,purchaseTime,overInsuranceTime'
					).getTemp(),
					db.collection('tab_StorageInfo').field('_id,storageName,area').getTemp(),
					db.collection('tab_EquipmentTotalClassify').field('_id,totalKeyName,totalKeyValue').getTemp(),
					db.collection('tab_EquipmentClassify').field(
						'_id,classifyName,classifyNickName,directoryCategories,directoryIndex').getTemp(),
					db.collection('tab_EquipmentFirms').field('_id,firmName').getTemp()
				],
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {
						"equipmentStateInfo_localdata": [{
								"text": "建档阶段",
								"value": 0
							},
							{
								"text": "在库可用",
								"value": 1
							},
							{
								"text": "领用出库",
								"value": 2
							},
							{
								"text": "上报故障",
								"value": 3
							},
							{
								"text": "确认故障",
								"value": 4
							},
							{
								"text": "维修中",
								"value": 5
							},
							{
								"text": "已报废",
								"value": 6
							},
							{
								"text": "禁止使用",
								"value": 7
							}
						]
					},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "tab_EquipmentInfo.xls",
					"type": "xls",
					"fields": {
						"装备名称": "equipmentName",
						"装备图片": "imgFile",
						"装备参数": "equipmentParameter",
						"使用方法": "useMethod",
						"备注": "remark",
						"在库状态": "storageState",
						"装备状态信息": "equipmentStateInfo",
						"装备购入时间": "purchaseTime",
						"装备过保时间": "overInsuranceTime"
					}
				},
				exportExcelData: [],
				qrcodeID: ""
			}
		},
		onLoad() {
			this._filter = {}
		},
		onReady() {
			this.$refs.udb.loadData()
		},
		methods: {
			onqueryload(data) {
				this.exportExcelData = data
				// console.log(data)
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			getIdLastThree(id) {
				const res = id ? id.slice(-3) : ''
				return res.toUpperCase();
			},
			tagTotalClassifyContent(content) {
				// 根据Tag内容返回相应的type
				if (content === 'A01') {
					return 'success';
				} else if (content === 'B02') {
					return 'warning';
				} else if (content === 'C03') {
					return 'primary';
				} else if (content === 'D04') {
					return 'danger';
				} else {
					return 'primary'; // 默认类型
				}
			},
			tagCategoryContent(content) {
				// 根据Tag内容返回相应的type
				if (content === '市级') {
					return 'success';
				} else if (content === '县级') {
					return 'warning';
				} else if (content === '乡级') {
					return 'danger';
				} else {
					return 'primary'; // 默认类型
				}
			},
			tagStorageContent(content) {
				// 根据Tag内容返回相应的type
				if (content === true) {
					return 'success';
				} else {
					return 'warning';
				}
			},
			createQRCode(id) {
				//打开二维码弹窗,调用生成二维码功能
				console.log(id)
				this.qrcodeID = id
				this.$refs.qrcodePopup.open('center')
			},
			drawQRCode(dataInfo) {
				var qr = new UQRCode();
				// 设置二维码内容
				qr.data = "https://www.baidu.com";
				// 设置二维码大小，必须与canvas设置的宽高一致
				qr.size = 200;
				// 调用制作二维码方法
				qr.make();
				// 获取canvas上下文
				var canvasContext = uni.createCanvasContext('qrcode', this); // 如果是组件，this必须传入
				// 设置uQRCode实例的canvas上下文
				qr.canvasContext = canvasContext;
				// 调用绘制方法将二维码图案绘制到canvas上
				qr.drawCanvas();
			}
		}
	}
</script>

<style>
	.equipmentStateInfo {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.qrcodeContainer {
		width: 300px;
		height: 300px;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}
</style>